<template>
    <yh-dialog
        :visible.sync="visibleTemp"
        v-bind="$attrs"
        title="查看详情"
        :modal="false"
        :close-on-click-modal="false"
        drag
        zoomable
        width="70vw"
        @close="handleCloseDialog"
        top="10vh"
    >
        <div class="dialog-main">
            <div class="table">
                <el-row>
                    <el-col :span="3">条目编码</el-col>
                    <el-col :span="5">
                        {{ basicInfo.entryCode }}
                    </el-col>
                    <el-col :span="3">条目名称</el-col>
                    <el-col :span="13">
                        {{ basicInfo.entryName }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="3">估值日期</el-col>
                    <el-col :span="5">
                        {{ dateFormat(basicInfo.valuationDate) }}
                    </el-col>
                    <el-col :span="3">触警类型</el-col>
                    <el-col :span="13" style="color: #dd2826">
                        {{ ThresholdType[basicInfo.triggerType] }}
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="3">连续违规天数</el-col>
                    <el-col :span="5"> {{ basicInfo.prohibitionDate }}天 </el-col>
                    <el-col :span="3">计算结果</el-col>
                    <el-col :span="5">
                        {{ basicInfo.resultString }}
                    </el-col>
                    <el-col :span="3">条目触发值</el-col>
                    <el-col :span="5">
                        {{ basicInfo.thresholdValue }}
                    </el-col>
                </el-row>
            </div>

            <RiskTable
                ref="risk-table"
                style="height: 400px"
                :tableData="tableData"
                :tableConfig="tableConfig"
                :column="columns"
                :stripe="false"
                v-loading="tableLoading"
                :key="tableKey"
                @page-change="getTableData"
            >
                <template #expand="{ row }">
                    <div v-if="row.detail && row.detail.length">
                        <vxe-table
                            class="detail-table"
                            :data="pagingProxy(row.detail, row.paging)"
                            show-header-overflow
                            :auto-resize="true"
                            resizable
                        >
                            <vxe-column
                                v-for="item in row.columns"
                                :field="item.val"
                                :title="item.name"
                                :key="item.val + table2Key"
                                show-overflow="tooltip"
                            >
                            </vxe-column>
                        </vxe-table>
                        <RiskPagination :paging="row.paging"></RiskPagination>
                    </div>
                </template>

                <template #entryCalculateFactorCode="{ row }">
                    {{
                        row.entryCalculateFactorCode +
                            ' ' +
                            (factorPojo[row.entryCalculateFactorCode] ? factorPojo[row.entryCalculateFactorCode].entryCalculateFactorName : '')
                    }}
                </template>
            </RiskTable>
        </div>
        <div slot="footer" class="dialog-footer" style="text-align: right; padding-right: 20px">
            <el-button size="mini" @click="handleCloseDialog"> 关 闭 </el-button>
            <!-- <el-button size="mini" type="primary" @click="handleSave">保 存 </el-button> -->
        </div>
    </yh-dialog>
</template>
<script lang="ts">
import { dateFormat, getConfigItem, numberFormat, timeFormat } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Component, Prop, PropSync, Vue, Watch } from 'vue-property-decorator';
import { ColumnVO, PageVO, TableConfigVO } from '@/common/vo';
import RiskTable from '@/common/components/risk-table-plus.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import { getFactorDetail } from '@/pages/quota/api';
import DictionConstUtil from '@/utils/diction-const-util';

@Component({ name: 'StaticDetail', components: { RiskTable, RiskPagination } })
export default class StaticDetail extends Vue {
    @PropSync('visible') syncVisible: boolean;
    @Prop() resultId: any;
    @Prop() history: any;

    dateFormat = dateFormat;

    ThresholdType = DictionConstUtil.ThresholdType;

    public visibleTemp: boolean = false;

    confirmEnum: any = {
        '0': '否',
        '1': '是',
        '2': '含待确认',
    };

    basicInfo: any = {
        entryCode: '',
        entryName: '',
        valuationDate: '',
        triggerType: '',
        prohibitionDate: '',
        resultString: '',
        thresholdValue: '',
    }; // 基础信息

    tableLoading: boolean = true;
    tableData: any[] = [];
    tableConfig: TableConfigVO = {
        rowKey: 'key', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    columns: ColumnVO[] = [
        {
            type: 'expand', // 展开
            align: 'center',
            width: 50,
        },
        {
            title: '流水号',
            field: 'resultId',
            minWidth: 100,
        },
        {
            title: '条目编码',
            field: 'entryCode',
            minWidth: 100,
        },
        {
            title: '分支名称',
            field: 'branchName',
            minWidth: 250,
        },
        {
            title: '分支值',
            field: 'branchValueString',
            minWidth: 200,
        },
        {
            title: '分支序号',
            field: 'branchNo',
            minWidth: 80,
        },
        {
            title: '计算因子',
            field: 'entryCalculateFactorCode',
            minWidth: 200,
        },
        {
            title: '估值数据是否确认',
            field: 'confirm',
            minWidth: 140,
            render: (value, record) => this.confirmEnum[value],
        },
    ];
    // paging: PageVO = { pageSize: 25, currentPage: 1, total: 0 };

    factorPojo: any = {}; // 计算因子

    created() {}

    async mounted() {
        // 计算因子
        let factors = (await DictionConstUtil.FNCalculateFactor()) as any;
        for (let value of factors) {
            this.factorPojo[value.entryCalculateFactorCode] = value;
        }

        this.getTableData();
    }

    @Watch('visible', { immediate: true, deep: true })
    onWatchVisible(value) {
        if (value !== this.visibleTemp) {
            this.visibleTemp = value;
        }
    }

    getTableData(): void {
        this.tableLoading = true;
        const url = this.history ? '/event/history/branch/' : '/event/today/branch/';
        this.$axios({ method: 'get', url: url + this.resultId })
            .then((res: any) => {
                // res = [
                //     {
                //         branchKey: '12:YH1236:5:7:19:0',
                //         branchName: '资产单元净资产',
                //         branchNo: '5',
                //         branchValue: 1000,
                //         entryCalculateFactorCode: 'YH517',
                //         entryCode: 'YH1236',
                //         resultId: 1663461062,
                //         staticDetails: '[{"N_NET_ASSET":1000,"C_FUND_CODE":"2001","C_ASSET_CODE":"19"}]',
                //     },
                //     {
                //         branchKey: '12:YH1236:3:7:19:0',
                //         branchName: '证券持仓市值',
                //         branchNo: '3',
                //         branchValue: 300,
                //         entryCalculateFactorCode: 'YH801',
                //         entryCode: 'YH1236',
                //         resultId: 1663461062,
                //         staticDetails:
                //             '[{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"600019 SS","C_ISSUE_CODE":"1046","N_POSITION_ID":117838300,"C_ASSET_CODE":"19","C_ORIGINAL_HOLDER":"1046"},{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"163847 SS","C_ISSUE_CODE":"41126","N_POSITION_ID":121,"C_ASSET_CODE":"19"},{"C_FUND_CODE":"2001","D_POSITION_DATE":20210129,"N_MARKET_VALUE":100,"C_STOCK_CODE":"164847 SS","N_POSITION_ID":45,"C_ASSET_CODE":"19"}]',
                //     },
                // ];

                // 获取基础信息
                this.basicInfo = res[0];
                // 处理详情数据
                for (let i = 0; i < res.length; i++) {
                    let detail = JSON.parse(res[i].staticDetails);
                    res[i].key = res[i].branchKey + res[i].branchNo;
                    res[i].detail = detail;
                    res[i].paging = { pageSize: 25, currentPage: 1, total: detail ? detail.length : 0 };
                    res[i].columns = this.getFactorHead(res[i]);
                }
                res.sort((a, b) => Number(a.branchNo) - Number(a.branchNo));
                this.tableData = res;
                console.log(this.tableData, 'this.tableData');

                // 获取前提
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 获取指标静态表头
     */
    getFactorHead(data): any[] {
        // 优先展示字段，使用正则替换排序，不支持小数
        let fieldSort = ['C_FD_PRODUCT_CODE', 'C_FUND_CODE', 'C_STOCK_CODE'];
        // 除去优先展示的字段 其余字段使用正则排序的字段排序字段 不支持小数
        let fieldNoSort = ['C_PRODUCT_CODE'];

        let factor = this.factorPojo[data.entryCalculateFactorCode];
        if (!factor) {
            this.yh_message_error('未找到相关计算因子,分支明细解析失败！');
            return [];
        }
        try {
            // 静态字段
            let staticCalConfig = factor.staticCalConfig.split(';');
            // 字段对应名称
            let columnsNames = factor.columnsNames.split(';');

            let descript = {};
            console.log(columnsNames, 'columnsNames');

            for (let i = 0; i < columnsNames.length; i++) {
                let tablename = columnsNames[i]
                    .substr(0, columnsNames[i].indexOf(':'))
                    .replace(/\\r\\n/g, '')
                    .trim();
                let fields = columnsNames[i].substr(columnsNames[i].indexOf(':') + 1).split(',');
                this.$set(descript, tablename, {});
                for (let j = 0; j < fields.length; j++) {
                    descript[tablename][fields[j].substr(0, fields[j].indexOf('\\'))] = fields[j].substr(fields[j].indexOf('\\') + 1);
                }
            }
            let columnfield = descript[staticCalConfig[0]];
            let columns = [];
            for (let key in columnfield) {
                if (fieldSort.includes(key)) {
                    continue;
                }
                if (fieldNoSort.includes(key)) {
                    columns.push({
                        name: columnfield[key],
                        val: key,
                        minWidth: 150,
                    });
                } else {
                    columns.push({
                        name: columnfield[key],
                        val: key,
                        minWidth: 150,
                        type: 'func',
                        funcBody: (value, row, val) =>
                            value != undefined && val.toString().substr(0, 2) == 'N_'
                                ? numberFormat(value, 2)
                                : val.toString().substr(0, 2) == 'D_'
                                ? dateFormat(value)
                                : value || '--',
                    });
                }
            }

            // 优先展示字段
            for (let i = fieldSort.length - 1; i > -1; i--) {
                if (columnfield[fieldSort[i]]) {
                    columns.unshift({
                        name: columnfield[fieldSort[i]],
                        val: fieldSort[i],
                        width: 150,
                        // search: true,
                        // filters: [{ data: '' }],
                    });
                }
            }

            // obc字段
            if (data && data.staticDetails && data.staticDetails !== '[]') {
                let staticDetails = JSON.parse(data.staticDetails);
                if (staticDetails && staticDetails.length > 0 && staticDetails[0].OBC) {
                    for (let i = 0; i < staticDetails[0].OBC.length; i++) {
                        let extraFieldData = staticDetails[0].OBC[i];
                        columns.push({
                            name: extraFieldData.columnDesc ? extraFieldData.columnDesc : '未知',
                            val: 'OBC[' + i + '].columnValue',
                            width: 200,
                            // search: true,
                            // filters: [{ data: '' }],
                        });
                    }
                }
            }
            columns = columns.filter(ele => !['持仓编号', '持仓序号'].includes(ele.name));
            return columns;
        } catch (e) {
            // this.yh_message_error('分支明细解析失败！');
            console.log(e);
            return [];
        }
    }

    /**
     * 分页代理
     */
    pagingProxy(list, page): any[] {
        console.log(list, page, 'list, page');

        return list.slice((page.currentPage - 1) * page.pageSize, page.currentPage * page.pageSize);
    }

    /**
     * 保存事件
     */
    handleSave(): void {}

    /**
     * 关闭dialog事件
     */
    handleCloseDialog(): void {
        this.syncVisible = false;
    }
}
</script>
<style lang="scss" scoped>
.table {
    border-top: 1px solid rgba(239, 239, 239, 1);
    margin-bottom: 20px;
    .el-row {
        border-right: 1px solid rgba(239, 239, 239, 1);
        display: flex;
        .el-col {
            border: 1px solid rgba(239, 239, 239, 1);
            border-top: none;
            border-right: none;
            padding: 5px 5px;
            min-height: 32px;
            font-size: 12px;
            display: flex;
            align-items: center;
        }
        .el-col-3 {
            justify-content: center;
            background: #f7f8fc;
        }
        .el-col-5,
        .el-col-13 {
            padding-left: 10px;
        }
    }

    .textarea {
        .el-col {
            min-height: 85px;
        }
        .el-col-5 {
            flex-direction: column;
        }
    }
}
</style>
